/* Copyright 2024 Coremail
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import { SendMailResponse } from '../response/send_mail_response';
import { TaskBase } from './task_base';
import { SoapXmlReader, SoapXmlWriter } from '../xml/soap_xml';
import { MailMessage, MailMessageResp } from '../model/mail_message';
import { SendMailRequest } from '../request/send_mail_request';

export class SendMailTask extends TaskBase<SendMailRequest, SendMailResponse, MailMessage, MailMessageResp> {
  public async execute(): Promise<SendMailResponse> {
    let writer: SoapXmlWriter = new SoapXmlWriter();
    this.request.writeToXml(writer);
    return new Promise<SendMailResponse>((resolve: Function, reject: Function) => {
      this.httpClient.request({ extraData: this.request.xmlToString(writer) })
        .then((data: http.HttpResponse) => {
          if (this.isSuccessfully(data)) {
            let resp: SendMailResponse = new SendMailResponse();
            let reader: SoapXmlReader = new SoapXmlReader();
            resp.readFromXml(reader);
            resolve(resp);
          } else {
            reject(this.handleHttpStatusError(data));
          }
        }).catch((err: BusinessError) => {
        reject(this.handleHttpError(err));
      });
    });
  }
}
